package com.wyw.i18n.learning.constant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.EnumSet;

/**
 * @Title   响应结果枚举
 * @Description
 * @Author Mr Wu yewen.wu.china@gmail.com
 * @Date 2024/3/28 14:00
 * Update History:
 * Author        Time            Content
 */
public enum ResponseStatusEnum {

    SUCCESS(200, true, "success"),
    FAILED(500, false, "failed"),
    AUTH_NO_USER(501, false, "auth.no.user")

    ;


    // 响应业务状态
    private Integer status;
    // 调用是否成功
    private Boolean success;
    // 需与配置文件中的信息msg值一致
    private String msg;

    ResponseStatusEnum(Integer status, Boolean success, String msg) {
        this.status = status;
        this.success = success;
        this.msg = msg;
    }

    private MessageSource messageSource;

    public ResponseStatusEnum setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
        return this;
    }

    //通过静态内部类的方式注入bean，并赋值到枚举中
    @Component
    public static class ReportTypeServiceInjector {
        @Autowired
        private MessageSource messageSource;
        @PostConstruct
        public void postConstruct() {
            for (ResponseStatusEnum rt : EnumSet.allOf(ResponseStatusEnum.class))
                rt.setMessageSource(messageSource);
        }
    }

    /**
     * @return the status
     */
    public int getStatus() {
        return status;
    }

    /**
     * @return the msg，根据语言环境返回国际化字符串
     */
    public String getMsg() {
        return messageSource.getMessage(msg,null,msg, LocaleContextHolder.getLocale());
    }


}
